//
//  SettingViewController.m
//  MoreFunTV
//
//  Created by admin on 2014-10-24.
//  Copyright (c) 2014年 admin. All rights reserved.
//

#import "SettingViewController.h"
#import "AppDelegate.h"

@interface SettingViewController ()
{
    __weak MatchstickDeviceController *_matchstickDeviceController;
}
@end

@implementation SettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
     // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    AppDelegate *delegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
    _matchstickDeviceController = delegate.matchstickDeviceController;
    //投射图标判断
    if (_matchstickDeviceController.deviceScanner.devices.count > 0) {
        self.navigationItem.rightBarButtonItem = _matchstickDeviceController.matchstickBarButton;
    }
    
    //标题自定义
    [self customNavTitle];
    
    //设置列表
    [self setUpView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _matchstickDeviceController.delegate = self;
    
    SetUpSingleton *set = [SetUpSingleton sharedSetUp];
    //保存历史记录的标记
    if ([SetUpUdf readSetUpNSUdSaveHistoryFlag].length != 0)
    {
        set.strHistoryFlag = [SetUpUdf readSetUpNSUdSaveHistoryFlag] ;
    }
    //保存播放记录的标记
    if ([SetUpUdf readSetUpNSUdSavePlayFlag].length != 0)
    {
        set.strPlayFlag = [SetUpUdf readSetUpNSUdSavePlayFlag] ;
    }
    //启用移动网络时通知
    if ([SetUpUdf readSetUpNSUdNetFlag].length != 0)
    {
        set.strNetFlag = [SetUpUdf readSetUpNSUdNetFlag] ;
    }
    //消息通知
    if ([SetUpUdf readSetUpNSUdInfoFlag].length != 0)
    {
        set.strInfoFlag = [SetUpUdf readSetUpNSUdInfoFlag] ;
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        _cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
        _files = [[NSFileManager defaultManager] subpathsAtPath:_cachPath];
    });
}

- (void)shouldDisplayModalDeviceController {
    //投射按钮调用的方法
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myDevice" object:nil userInfo:nil];
}

- (void)didDiscoverDeviceOnNetwork {
    // Add the Matchstick icon if not present.
    self.navigationItem.rightBarButtonItem = _matchstickDeviceController.matchstickBarButton;
}

//标题自定义
-(void)customNavTitle
{
    UIButton *btnBack = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 44)];
    [btnBack setTitle:MyLocalizedString(@"setting") forState:UIControlStateNormal];
    btnBack.titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
    [btnBack setBackgroundColor:[UIColor clearColor]];
    [btnBack setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnBack addTarget:self action:@selector(btnBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"return.png"]];
    image.frame = CGRectMake(0, 12, 10, 20);
    [btnBack addSubview:image];
}

-(void)setUpView
{
    UIView *aView = [[UIView alloc]init];
    [self.view addSubview:aView];
    
    UITableView *tableSetUp = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight-64) style:UITableViewStyleGrouped];
    tableSetUp.showsVerticalScrollIndicator = NO;//隐藏纵向滚动条
    tableSetUp.delegate = self;
    tableSetUp.dataSource = self;
    tableSetUp.bounces = NO;
    [tableSetUp setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [tableSetUp setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:tableSetUp];
}

//列表每行显示的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = @"firstTable";
    int section = (int)[indexPath section];
    int row = (int)[indexPath row];

    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier:identifier];
    [cell setBackgroundColor:[UIColor whiteColor]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:18.0f];
 
    UIView *viewLine = [[UIView alloc]initWithFrame:CGRectMake(15, 49, kScreenWidth, 1)];
    viewLine.backgroundColor = [UIColor colorWithRed:204/255.0 green:204/255.0  blue:204/255.0  alpha:1.000];//分割线颜色
    [cell addSubview:viewLine];
    
    UISwitch *switchChoose = [[ UISwitch alloc]initWithFrame:CGRectMake(kScreenWidth-66,9,0,0)];
    [switchChoose setOn:NO animated:YES];
    switchChoose.onTintColor = [UIColor blueColor];
    [switchChoose addTarget:self action:@selector(swichChanged:) forControlEvents:UIControlEventValueChanged];
    [cell addSubview:switchChoose];
    
    //单例模式
    SetUpSingleton *set = [SetUpSingleton sharedSetUp];
    switch (section) {
        case 0:
            if (row == 0) {
                switchChoose.tag = 111;
                cell.textLabel.text = MyLocalizedString(@"textinfo1");
                if ([set.strNetFlag isEqual:@"NO"]) {
                    [switchChoose setOn:NO animated:YES];
                }else{
                    [switchChoose setOn:YES animated:YES];
                }
            }
            else{
                switchChoose.tag = 122;
                cell.textLabel.text = MyLocalizedString(@"textinfo2");
                if ([set.strInfoFlag isEqual:@"NO"]) {
                    [switchChoose setOn:NO animated:YES];
                }else{
                    [switchChoose setOn:YES animated:YES];
                }
            }
            break;
        case 1:
            if (row == 0) {
                [switchChoose setHidden:YES];
                cell.textLabel.text = MyLocalizedString(@"textinfo3");
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                
                _labCount = [[UILabel alloc]initWithFrame:CGRectMake(180, 0, kScreenWidth-30-180, 50)];
                _labCount.textColor = [UIColor blackColor];
                _labCount.text = [NSString stringWithFormat:@"%d.0k",[_files count]];
                _labCount.font = [UIFont systemFontOfSize:18.0f];
                _labCount.textAlignment = NSTextAlignmentRight;
                _labCount.backgroundColor = [UIColor clearColor];
                [cell addSubview:_labCount];
            }
            else if (row == 1){
                switchChoose.tag = 133;
                cell.textLabel.text = MyLocalizedString(@"textinfo4");
                if ([set.strPlayFlag isEqual:@"NO"]) {
                    [switchChoose setOn:NO animated:YES];
                }else{
                    [switchChoose setOn:YES animated:YES];
                }
            }
            else{
                switchChoose.tag = 144;
                cell.textLabel.text = MyLocalizedString(@"textinfo5");
                if ([set.strHistoryFlag isEqual:@"NO"]) {
                    [switchChoose setOn:NO animated:YES];
                }else{
                    [switchChoose setOn:YES animated:YES];
                }
            }
            break;
        default:
            [switchChoose setHidden:YES];
            cell.textLabel.text =  MyLocalizedString(@"textinfo6");
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            break;
    }
    return cell;
}

//cell的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && indexPath.row == 0){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:MyLocalizedString(@"alertinfo1") message:MyLocalizedString(@"alertinfof") delegate:self cancelButtonTitle:MyLocalizedString(@"cancel") otherButtonTitles:MyLocalizedString(@"sure"), nil];
        [alert show];
    }
    else if (indexPath.section == 2 && indexPath.row == 0)
    {
        AboutViewController *about = [[AboutViewController alloc]init];
        [self.navigationController pushViewController:about animated:YES];
    }
}

//选择按钮事件
-(void)swichChanged:(UISwitch *)sender
{
    SetUpSingleton *set = [SetUpSingleton sharedSetUp];
    switch (sender.tag) {
        case 111:
            if (sender.on){
                set.strNetFlag = @"YES";
            }
            else{
                set.strNetFlag = @"NO";
            }
            //写入设置记录  启用网络
            [SetUpUdf writeSetUpNSUdNetFlag:set.strNetFlag];
            break;
        case 122:
            if (sender.on){
                set.strInfoFlag = @"YES";
            }
            else{
                set.strInfoFlag = @"NO";
            }
            //写入设置记录  消息通知
            [SetUpUdf writeSetUpNSUdInfoFlag:set.strInfoFlag];
            break;
        case 133:
            if (sender.on){
                set.strPlayFlag = @"YES";
            }
            else{
                set.strPlayFlag = @"NO";
            }
            //写入设置记录  播放记录
            [SetUpUdf writeSetUpNSUdSavePlay:set.strPlayFlag];
            break;
        default:
            if (sender.on){
                set.strHistoryFlag = @"YES";
            }
            else{
                set.strHistoryFlag = @"NO";
            }
            //写入设置记录  历史记录
            [SetUpUdf writeSetUpNSUdSaveHistory:set.strHistoryFlag];
            break;
    }
}

//清空历史记录
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        for (NSString *p in _files){
            NSError *error;
            NSString *path = [_cachPath stringByAppendingPathComponent:p];
            if ([[NSFileManager defaultManager] fileExistsAtPath:path]){
                [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
            }
            _labCount.text = @"0.0k";
        }
        
        //清除缓存
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [appDelegate.myCache clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
    }
}

//设置每个分区多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    }
    else if (section == 1){
        return 3;
    }
    else{
        return 1;
    }
}

//返回分组的个数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

//分组自定义
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, kScreenWidth, 35)];
    lab.backgroundColor = [UIColor clearColor];
    lab.textColor = [UIColor colorWithWhite:0.598 alpha:1.000];
    if (section == 0) {
        lab.text = MyLocalizedString(@"info");
    }
    else if (section == 1){
        lab.text = MyLocalizedString(@"secret");
    }
    else{
        lab.text = MyLocalizedString(@"about");
    }
    lab.font = [UIFont boldSystemFontOfSize:17.0f];
    
    UIView *viewLine = [[UIView alloc]initWithFrame:CGRectMake(15, 34, kScreenWidth-15, 1)];
    viewLine.backgroundColor = [UIColor colorWithRed:204/255.0 green:204/255.0  blue:204/255.0  alpha:1.000];//分割线颜色
    [lab addSubview:viewLine];
    return lab;
}

//设置标题高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;
}

//列表每行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

//尾部标题的高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

-(void)btnBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
